package com.woniuxy.redis.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.net.UnknownHostException;

/**
 * @Author: linKe
 * @Date: 2022/1/5 11:09
 * @FileName: RedisConfiguration
 * @version: 1.0
 * @Description: Redis序列化配置类
 * 配置redisTemplate的序列化参数类型
 * key 为String
 * value 为JSON （redis默认的json）
 */
@Configuration
public class RedisConfiguration {

    /**
     * 配置redisTemplate序列化
     *
     * @param redisConnectionFactory redis 连接工厂
     * @return 结果
     * @throws UnknownHostException 未知主机异常
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(RedisSerializer.json());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }

    /**
     * 配置redisCache 缓存的序列化格式器
     * 跟String底层返回的是一样的
     * @return 结果
     */
    @Bean
    public static RedisCacheConfiguration defaultCacheConfig() {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration =
                redisCacheConfiguration
                        //配置keys 的序列化为Redis的string
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
                        //配置Values 的序列化为Redis的json
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));


        return redisCacheConfiguration;
    }

}
